package cn.git.socket.handler;

import cn.git.entity.Product;
import cn.git.mapper.ProductMapper;
import cn.git.socket.SocketUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @description: socket请求处理类
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-09-27
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SocketHandler implements Runnable {

    /**
     * 订单信息mapper
     */
    private ProductMapper productMapper;

    /**
     * 客户端socket
     */
    private Socket clientSocket;

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @SneakyThrows
    @Override
    public void run() {
        // 获取请求数据信息
        System.out.println("接收数据开始处理!");
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

        // 读取数据前6位，获取请求数据长度
        char[] bodyBytes = new char[6];
        in.read(bodyBytes);
        String dataLengthStr = new String(bodyBytes);

        // 获取请求数据信息
        int dataLength = Integer.parseInt(dataLengthStr);
        System.out.println("请求数据长度:" + dataLength);

        bodyBytes = new char[dataLength];
        in.read(bodyBytes);
        String requestBodyInfo = new String(bodyBytes);
        System.out.println("请求数据:" + requestBodyInfo);

        // 请求数据转换为Person对象
        Product product = JSON.parseObject(requestBodyInfo, Product.class);
        product.setId(IdUtil.simpleUUID());
        productMapper.insert(product);

        // 响应数据
        String rspJSONInfo = JSONObject.toJSONString(product);

        // 响应数据长度标识位 eg: 000667
        String prefixLength = SocketUtil.leftFixedZero(6, rspJSONInfo.length());

        // 最终响应数据
        String finalRspInfo = prefixLength.concat(rspJSONInfo);
        System.out.println("响应数据:" + finalRspInfo);
        out.println(finalRspInfo);
    }
}
